package servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取文件路径
        String realPath = getServletContext().getRealPath("/files/index.png");
        File file = new File(realPath);
        FileInputStream inputStream = new FileInputStream(file);
        // 获取文件MIME信息
        String mimeType = getServletContext().getMimeType(realPath);
        System.out.println(mimeType);
        resp.setContentType(mimeType);
        //设置下载文件的名字
        String filename = "tu.png";
        String encodeName = URLEncoder.encode(filename, "UTF-8");
        // 创建Content-Disposition信息
        String disposition = "attachment; filename =" + encodeName;
        // 获取文件长度
        long size = file.length();

        resp.setHeader("Content-Disposition", disposition);
        resp.setContentLength((int) size);
        // 通过response获取输出流，用于向浏览器输出内容
        ServletOutputStream outputStream = resp.getOutputStream();
// 将文件输入流通过输出流输出
        byte[] bs = new byte[1024];
        int len = -1;
        while ((len = inputStream.read(bs)) !=-1) {
            outputStream.write(bs, 0, len);
        }
        outputStream.close();
        inputStream.close();
    }
}
